/**
 * 用于(项目/产品)各自单独自定义的js工具类
 **/
var mytools = {};

/**
 * 清空数据，按照样式清空；
 * 1）按照form表单Id清空：id参数#开头
 * 2）按照form表单class样式清空：id参数.开头
 */
mytools.cleanData=function(id){
	$(id).find(".clean").val("");
	$(id).find("IMG").each(function(){
		$(this).attr("src",strUtil.doNull($(this).attr("data-def"), ctx+"/images/plateform/def.jpg"));
		//$(this).next().text("选择主图");
		$(this).siblings("label").eq(2).text("");
		$(this).siblings("a").text("");
	});
}

/**
 * 清空校验规则提示信息，按照样式清空；
 * 1）按照form表单Id清空：id参数#开头
 * 2）按照form表单class样式清空：id参数.开头
 */
mytools.cleanValidate=function(id){
	var validate = $(id).data('bootstrapValidator').validate();
	validate.resetForm();
}
/**
 * 关闭模态窗口
 */
mytools.closeModal=function(id){
	$('#'+id).modal('hide');
}
// 选中下拉框项的text赋值给指定元素value
mytools.setSelectText=function(obj,id){
    var selectedText = $(obj).find("option:selected").text();
    $(id).val(selectedText);
}
//选中下拉框项的value赋值给指定元素value
mytools.setSelectValue=function(obj,id){
    var selectedVal = $(obj).find("option:selected").val();
    $(id).val(selectedVal);
}
//选中下拉框项的value和text赋值给指定元素value
mytools.setSelectValueText=function(obj,id_val,id_text){
    var selectedObj = $(obj).find("option:selected");
    $(id_val).val(selectedObj.val());
    $(id_text).val(selectedObj.text());
}

//调用参考： onchange="mytools.setSelectOther(this,'user-ename','#addForm1_orgCname')"
mytools.setSelectOther=function(obj,optAttr,id){
    var selectedAttr = $(obj).find("option:selected").attr(optAttr);
    $(id).val(selectedAttr);
}
//获取指定范围的日期
mytools.getDateByType=function(type){
    var nowDate = new Date();
    var beginDate='',endDate='';
    var dateRes = {'beginDate':'','endDate':''};
    // nowDate = new Date('2020-01-01');
    var y = nowDate.getFullYear(), m = nowDate.getMonth();
    if(type=='d'){//本日
        dateRes.beginDate = nowDate.format("yyyy-MM-dd");//周一
        dateRes.endDate = nowDate.format("yyyy-MM-dd");
    }else if(type=='w'){//本周
        var weekday = nowDate.getDay()||7; //获取星期几,getDay()返回值是 0（周日） 到 6（周六） 之间的一个整数。0||7为7，即weekday的值为1-7
        nowDate.setDate(nowDate.getDate()-weekday+1);//往前算（weekday-1）天，年份、月份会自动变化
        dateRes.beginDate = nowDate.format("yyyy-MM-dd");//周一
        nowDate.setDate(nowDate.getDate()+6);//周日
        dateRes.endDate = nowDate.format("yyyy-MM-dd");
    }else if(type=='m'){//本月
        nowDate.setDate(1);//本月第一天
        dateRes.beginDate= nowDate.format("yyyy-MM-dd");
        var lastDay = new Date(y, m + 1, 0);
        dateRes.endDate= lastDay.format("yyyy-MM-dd");
    }else if(type=='y'){//本年
        dateRes.beginDate = y + "-01-01";
        var day = new Date(y, 12, 0);
        dateRes.endDate =day.format("yyyy-MM-dd");
    }
    console.log('getDateByType',dateRes);
    return dateRes;
}
/**
 * 封装的pjax跳转方法1
 */
mytools.pjax=function(url,container,fragment){
	var defcon = ".content-wrapper";
	var a=defcon;
	var b=defcon;
	if(container!=undefined &&container!=null && container!=''){
		a = container;
	}
	if(fragment!=undefined &&fragment!=null && fragment!=''){
		b = fragment;
	}
	//alert(url+"  "+a+"  "+b);
	 $.pjax({  
         url: url,  
         container: a,  
         fragment: b,
         cache: false,
         //maxCacheLength:0,
         timeout: 8000
       })
}

/**
 * 封装的load跳转方法 常用按钮跳转
 */
mytools.load=function(url){
	var histClick = clickMenu;
	$.ajaxSetup ({cache: false});
	$(".content-wrapper").load(url+" .content-wrapper>",function(resultData){
		 $result = $(resultData);
        $result.find("script").appendTo(".content-wrapper");//保证子页面的js内容能被引入进来
        clickMenu = histClick;
        showClickMenu();
	});
}
//判断form表单中某字段输入值是否已重复（调用后台）
mytools.validFieldRepeat=function(obj){
    var thisObj = $(obj);
    var thisVal = thisObj.val();
    if(strUtil.isNull(thisVal)){
        return;
    }
    var fieldName = thisObj.attr("name");
    if(strUtil.isNull(fieldName)||fieldName.indexOf('.')<0){
        layer.msg('name属性配置不合法');
        return;
    }
    var formId = thisObj.parents("form").eq(0).attr("id");//获取当前元素所在父层级中的就近的formId
    if(strUtil.isNull(formId)<0){
        layer.msg(fieldName+'元素必须存放form表单内！');
        return;
    }
    console.log('formId->'+formId);
    var formObj =  $("#"+formId);
    var form_pageName = formObj.find("input[name='pageName']").val();
    var form_formName = formObj.find("input[name='formName']").val();
    var isEdit = false;//标记是否是修改表单
    if(form_formName=='editForm'){
        isEdit = true;
    }
    var fieldArr = fieldName.split(".");
    var objName = fieldArr[0];
    var condisStr = objName+".w_"+fieldArr[1];
    var pageName = strUtil.doNull(thisObj.attr("data-validate-repeat-page-name"),form_pageName);
    var formName = strUtil.doNull(thisObj.attr("data-validate-repeat-form-name"),'searchForm');
    var objMsg = strUtil.doNull(thisObj.attr("data-validate-repeat-message"),"此项输入的值已重复，请更换！");
    var isClean = strUtil.doNull(thisObj.attr("data-validate-repeat-clean"),'true');
    console.log('valid.req',pageName+'='+pageName+'&'+formName+'='+formName+'&'+condisStr+'='+thisVal);
    var selfInput = thisObj.attr("data-validate-repeat-selfname");
    var editRemoveId_name = '',editRemoveId_val='';
    if(isEdit){
        if(strUtil.isNull(selfInput)){
            layer.msg(formId+'下'+fieldName+'必须设置属性：data-validate-repeat-selfname');
            return;
        }
        var selfInputObj = formObj.find("input[name='"+selfInput+"']");
        if(!selfInputObj || strUtil.isNull(selfInputObj.val())){
            layer.msg(formId+"下"+fieldName+"input[name='"+selfInput+"']元素不存在或值为空！");
            return;
        }
        editRemoveId_name =selfInput.split('w_')[1];
        editRemoveId_val = selfInputObj.val();
        console.log('valid.type','edit->'+editRemoveId_name+'='+editRemoveId_val);
    }else{
        console.log('valid.type','add');
    }
    var index_load = layer.load(1, {shade: false});
    var paramLoadData = {};
    paramLoadData['pageName']=pageName;
    paramLoadData['formName']=formName;
    paramLoadData[condisStr]=thisVal;
    $.getJSON(common_list_url,paramLoadData, function(myData2){
        console.log('valid.res',myData2);
        layer.close(index_load);
        if(myData2.total>0){
            if(isEdit){
                //修改情况下，排除自己判断（自己改自己）
                var oldInfoIdVal = myData2.rows[0][objName][editRemoveId_name];
                if(editRemoveId_val==oldInfoIdVal){
                    return;
                }
            }
            console.log('valid.msg'+objMsg);
            layer.msg(objMsg);
            if(isClean=='true'){
                thisObj.val('');
                formObj.data('bootstrapValidator').updateStatus(fieldName,'NOT_VALIDATED',null).validateField(fieldName);
            }
        }
    });
}
/**
 * 站点以端口方式访问时，需要替换top连接地址
 * @param thisObj
 * @param findStr
 * @param newStr
 */
mytools.portRequestReplaceLink=function(thisObj) {
    if(window.location.port){
        //  console.log("请求方式：","因IP+端口方式，需top.html的a标签href地址内["+findStr+"] 替换为 ["+newStr+"]");
		var newStr = '/wcm/'+siteCode+'/';
		var findStr = '../../../';
        $("[data-repla-port-link='true']").find("a[href^='"+findStr+"']").each(function () {
            var regExpB=new RegExp(findStr,"g");
            $(this).attr("href",$(this).attr("href").replace(regExpB,newStr));
            // $(this).attr("href",$(this).attr("href").replace(/\..\/..\//g,"\/wcm\/ttwl\/"));
            // console.log($(this).text()+"-new-->",$(this).attr("href"));
        });
        $("[data-repla-port-link='true']").find("img[src^='"+findStr+"']").each(function () {
            var regExpB=new RegExp(findStr,"g");
            // console.log("old-->",$(this).attr("src"));
            $(this).attr("src",$(this).attr("src").replace(regExpB,newStr));
            // console.log("new-->",$(this).attr("src"));
        });
    }
}
$(function(){
    $("[data-temp-code]").each(function(){
        var thisObj = $(this);
        var objId = thisObj.attr("id");
        var code = thisObj.attr("data-temp-code");
        //console.log("加载["+siteCode+"]的["+code+"]栏目数据...");
        var tempType = thisObj.attr("data-temp-type");
        var dataTempRows = doNull(thisObj.attr("data-temp-rows"),5);
        var dataTempHeight = doNull(thisObj.attr("data-temp-height"),"200px");//默认高度
        var dataDefVal = doNull(thisObj.attr("data-temp-def"),"/images/def6.jpg");
        var dataTempCols = doNull(thisObj.attr("data-temp-cols"),"12");

        //alert(objId+"|"+code+"|"+tempType+"|"+dataTempRows);

        var tempId = objId;
        if(!isNull(tempType)){
            tempId = tempType+"-template";
        }else{
            alert(objId+"缺少data-temp-type元素");
            return;
        }
        if("banner"==tempType || "bannerTitle"==tempType){
            //tempType=banner单独处理
            tempId = tempType+"-template";
            var objMap = {};
            objMap.objId=objId;
            objMap.code=code;
            objMap.tempId=tempId;
            objMap.dataTempRows=dataTempRows;
            objMap.dataTempHeight=dataTempHeight;
            objMap.dataDefVal = dataDefVal;
            objMap.dataTempCols = dataTempCols;
            loadBannerBox(objMap);
        }else if("thisId"==tempType){
            //tempType=data
            tempId = objId+"-template";
            $.getJSON("../data/"+code+".json",function(myData){
                myData.siteCode=siteCode;
                myData.dataTempRows=dataTempRows;
                myData.dataTempHeight=dataTempHeight;
                myData.dataDefVal = dataDefVal;
                myData.dataTempCols = dataTempCols;
                var htmlContent = baidu.template(tempId,eval(myData));
                $("#"+objId).html(htmlContent);
            });
        }else{
            $.ajaxSetup ({cache: false});
            $.getJSON("../data/"+code+".json",function(myData){
                myData.siteCode=siteCode;
                myData.dataTempRows=dataTempRows;
                myData.dataTempHeight=dataTempHeight;
                myData.dataDefVal = dataDefVal;
                myData.dataTempCols = dataTempCols;
                var htmlContent = baidu.template(tempId,eval(myData));
                $("#"+objId).html(htmlContent);
            });
        }
    });

    $("[data-repla-port-link='true']").each(function () {
        mytools.portRequestReplaceLink($(this));
    });

});


//加载CMS发布的栏目数据，作为Banner images
function loadBannerBox(paramMap){
    $.getJSON("../data/"+paramMap["code"]+".json",function(myData){
        console.log(myData);
        //解析数据
        myData.siteCode=siteCode;
        myData.dataTempRows=paramMap["dataTempRows"];
        myData.dataTempHeight=paramMap["dataTempHeight"];
        myData.dataDefVal = paramMap["dataDefVal"];
        myData.dataTempCols = paramMap["dataTempCols"];
        var dataHtml = baidu.template(paramMap["tempId"],eval(myData));
        var objId = paramMap["objId"];
        $("#"+objId).html(dataHtml);
        //初始化Banner 的滚屏插件 fullSlide
        $("#"+objId).find(".fullSlide").hover(function(){
                $(this).find(".prev,.next").stop(true, true).fadeTo("show", 0.5)
            },
            function(){
                $(this).find(".prev,.next").fadeOut()
            });
        $("#"+objId).find(".fullSlide").slide({
            titCell: ".hd ul",
            mainCell: ".bd ul",
            effect: "fold",
            autoPlay: true,
            autoPage: true,
            trigger: "click",
            startFun: function(i) {
                var curLi = jQuery(".fullSlide .bd li").eq(i);
                if ( !! curLi.attr("_src")) {
                    curLi.css("background-image", curLi.attr("_src")).removeAttr("_src")
                }
            }
        });
    });
}

function isNull(str){
    if(null==str||undefined==str){
        return true;
    }
    if(""==str||"null"==str||"undefined"==str||JSON.stringify(str).trim().length==0){
        return true;
    }
    return false;
}
function doNull(str, defVal){
    if(isNull(str)){
        return defVal;
    }
    return str;
}

